<?php

namespace addons\Laborer\merchant\controllers;

use Yii;
use common\traits\Curd;
use common\helpers\ExcelHelper;
use common\models\base\SearchModel;
use addons\Flow\common\models\Works;
use addons\Laborer\common\models\Laborer;
use yii\helpers\Json;


class DefaultController extends BaseController
{
    use Curd;

    public $modelClass = Laborer::class;

    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['member' => ['realname']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['member.realname'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $search = $params = Yii::$app->request->queryParams;
        $created_time = [];
        if(!empty($search['SearchModel']['created_at'])){
            list($start,$end) = explode('/',$params['SearchModel']['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between',$this->modelClass::tableName().'.created_at',$start,$end];
            unset($params['SearchModel']['created_at']);
        }
        $dataProvider = $searchModel->search($params);
        !empty($created_time)?$dataProvider->query
            ->andWhere($created_time):$dataProvider->query
            ->andFilterWhere([$this->modelClass::tableName().'.merchant_id' => $this->getMerchantId()]);
        if(Yii::$app->id == 'merchant'&&Yii::$app->user->identity->department_id!=0)
            $dataProvider->query
                ->andWhere([$this->modelClass::tableName().'.member_id' => Yii::$app->user->id])
                ->andFilterWhere([$this->modelClass::tableName().'.merchant_id' => $this->getMerchantId()]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionAjaxEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);
//        if ($this->findModel($id)->state)
//            return $this->message("已进入审核流程，不能编辑", $this->redirect(['index']), 'error');
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        $model->member_id = Yii::$app->user->id;
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            !empty($model->covers) && $model->covers = Json::encode($model->covers);
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('ajax-edit', [
            'model' => $model,
            'radioList' => $radioList,
        ]);
    }
    public function actionCreate()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);
//        if ($this->findModel($id)->state)
//            return $this->message("已进入审核流程，不能编辑", $this->redirect(['index']), 'error');
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        $model->member_id = Yii::$app->user->id;
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            !empty($model->covers) && $model->covers = Json::encode($model->covers);
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('create', [
            'model' => $model,
            'radioList' => $radioList,
        ]);
    }
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);
//        if ($this->findModel($id)->state)
//            return $this->message("已进入审核流程，不能编辑", $this->redirect(['index']), 'error');
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        $model->member_id = Yii::$app->user->id;
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            !empty($model->covers) && $model->covers = Json::encode($model->covers);
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('edit', [
            'model' => $model,
            'radioList' => $radioList,
        ]);
    }
    public function actionAjaxApprove()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        if ($model->load(Yii::$app->request->post())) {
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');

        }
        $status = explode('/',$model->status);
        $works = Works::find()->andWhere(['workflow_id'=>$status[0],'work_id'=>$id])->one();
        return $this->renderAjax('ajax-approve', [
            'model' => $model,
            'radioList' => $radioList,
            'status' =>$works->audit_id,
        ]);
    }

    public function actionDelete($id)
    {

        if($this->findModel($id)->state=='apply'){
            // 事务
            $transaction = Yii::$app->db->beginTransaction();
            try {
                Works::deleteAll(["workflow_id" => 'Laborer', 'work_id' => $id]);
                $this->modelClass::deleteAll(["state" => 'apply', 'id' => $id]);
                $transaction->commit();
                return $this->message("删除成功", $this->redirect(['index']));
            } catch (\Exception $e) {
                $transaction->rollBack();
                return(Yii::$app->request->referrer);
            }
        }
        return $this->message("已开始审核，不能删除", $this->redirect(['index']), 'error');
    }
    /**
     * 导出
     */
    public function actionExport()
    {
        $header = [
            ['数量', 'num'],
            ['理由', 'content'],
            ['申请人', 'member.realname'],
            ['申请日期', 'created_at', 'date', 'Y-m-d'],
            ['审批状态', 'state', 'function', function($model){
                $status=true;
                foreach ($model->getNextStatuses() as $key => $nextStatus) {
                    $status = false;
                }
                if($status) return $model->getWorkflowStatus()->getLabel();
                if(!$status) return \addons\Flow\common\enums\WorkflowEnum::getValue($model->state);
            }],
        ];
        $list = $this->modelClass::find()->select('*')
            ->andWhere(['merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->with('member')
            ->all();
        return ExcelHelper::exportData($list, $header);
    }
    protected function findModel($id)
    {
        if (empty($id) || empty(($model = $this->modelClass::findOne(['id' => $id, 'merchant_id' => $this->getMerchantId()])))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }
        return $model;
    }
}
